<?php

namespace App\Console\Commands;

use App\Models\DashAdmin;
use Dcat\Admin\Models\Administrator;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;

class DashAdminCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dash:admin {--add} {--remove} {--uuid=} {--username=} {--password=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Dash admin';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $uuid = $this->option('uuid');
        $username = $this->option('username');
        $password = $this->option('password');

        if (!$admin = Administrator::query()->first()) {
            $this->error("Not init system yet.");
            return 1;
        }

        $adminId = $admin->id;
        if ($this->option('add')) {
            if (!$uuid || !$username || !$password) {
                $this->error('UUID, Username, and Password are required for adding.');
                return 1;
            }
            if (DashAdmin::query()->where('username', $username)->exists()) {
                DashAdmin::query()->where('username', $username)->update([
                    'admin_id' => $adminId,
                    'uuid' => $uuid,
                    'password' => Hash::make($password)
                ]);
                $this->info('DashAdmin updated successfully.');
            } else {
                $dashAdmin = new DashAdmin();
                $dashAdmin->admin_id = $adminId;
                $dashAdmin->uuid = $uuid;
                $dashAdmin->username = $username;
                $dashAdmin->password = Hash::make($password);
                $dashAdmin->save();
                $this->info('DashAdmin added successfully.');
            }
        }

        if ($this->option('remove')) {
            if (!$uuid) {
                $this->error('Username is required for deleting.');
                return 1;
            }
        }

        return 0;
    }
}
